﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class main2 : System.Web.UI.MasterPage
{
    protected string sb="";
    BLL.Users blluser = new BLL.Users();
    protected MODEL.Users model = new MODEL.Users();
    protected BLL.Search bllsearch = new BLL.Search();
    protected void Page_Load(object sender, EventArgs e)
    {
        #region 绑定 加载热词
        //绑定 加载热词
        if (common.getKeyWord() != null)
        {
            rpHotWords.DataSource = common.getKeyWord();
            rpHotWords.DataBind();
        }
        #endregion

        //判断是否访问(登录过session不为空)，是否记住我
        if (!IsPostBack)
        {
            if (!common.isLoginOrNot())
            {
                modify.Visible = false;
                logOut.Visible = false;
            }
            else
            {
                //session不为null则显示
                show();
            }
        }

    }
    #region 注册
    /// <summary>
    /// 注册
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void register_Click(object sender, EventArgs e)
    {
        Response.Redirect("register.aspx");//注册按钮点击重定向到注册页面
    }
    #endregion

    #region 登录
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void login_Click(object sender, EventArgs e)
    {
        string name = txtName.Value.Trim();
        string pwd =common.GetMD5(txtPwd.Value.Trim());
         //根据name判断是否为管理员，如果是的话不用MD5加密然后再验证
        MODEL.Users User = new MODEL.Users();
        User = blluser.getModel(name);
        if (User != null)
        {
            if (User.UserRoleId == 2 || User.UserRoleId == 3)
            {
                pwd = txtPwd.Value.Trim();
            }

            //否则加密再验证
            else
            {
                pwd = common.GetMD5(txtPwd.Value.Trim());
            }

            //登录(用户名，密码正确则登录成功)
            if (blluser.Exist(name, pwd))
            {
                model = blluser.getModel(name);
                if (model != null)
                {
                    //把model实体对象保存到session中
                    Session["currentUser"] = model;
                    if (cbRemember.Checked)
                    {
                        HttpCookie cookieName = new HttpCookie("name", model.UName);
                        HttpCookie cookiePwd = new HttpCookie("pwd", common.Encrypt(common.GetMD5(model.Pwd), ""));
                        cookieName.Expires = DateTime.Now.AddYears(1);
                        cookiePwd.Expires = DateTime.Now.AddYears(1);
                        Response.Cookies.Add(cookieName);
                        Response.Cookies.Add(cookiePwd);
                    }
                    show();
                    //注意：：：登录成功再次跳转到请求页面  因为是先执行内容页的pageload方法，要想内容页也是登录的状态必须再次跳到内容页
                    Response.Redirect(Request.Url.ToString());
                }
            }
            else
            {
                MessageBox.Show(Page, "用户名或密码有错");
            }
        }
        else
        {
            MessageBox.Show(Page, "用户名不存在");
        }
    }
    #endregion

    #region 退出
    /// <summary>
    /// 退出
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void logOut_Click(object sender, EventArgs e)
    {
        common.LoginOut();
    } 
    #endregion

    #region 对控件的隐藏显示操作
    public void show()
    {
        retrieve.Visible = false;
        contentRT1.Visible = false;
        modify.Visible = true;
        //注意这里得用session来取id的值，不要直接有model
        modify.HRef = "modify.aspx?id=" + ((MODEL.Users)Session["currentUser"]).UId;
        logOut.Visible = true;
        sb="<marquee direction='up' scrolldelay='300' height='120px'><font size='4px'>欢迎您" + ((MODEL.Users)Session["currentUser"]).UName + "光临本站！</font></marquee>";
    }
    #endregion

    #region 提交（通过邮件重置密码）
    /// <summary>
    /// 提交（通过邮件重置密码）
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void divSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string name = divUsername.Value.Trim();
            string question = divDropDL.SelectedItem.Text.Trim();
            string answer = divAnswer.Value.Trim();
            if (blluser.isExistOrNotByQA(name, question, answer))
            {
                MODEL.Users model = blluser.getModel(name);
                try
                {
                    Mail.sendMail(model.Email, name);
                    MessageBox.Show(Page, "系统为您重置的密码已经发送到您的邮箱");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(Page, "发送邮件出现异常");
                    throw new Exception(ex.Message);
                }
            }
            else
            {
                MessageBox.Show(Page, "用户名不存在或密保问题有错，答案不正确");
            }
        }
    }
    #endregion

    #region 搜索
    /// <summary>
    /// 搜索
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSearch_Click(object sender, ImageClickEventArgs e)
    {
        //将搜索的词汇加入到数据库
        try
        {
            bllsearch.addKeyWord(txtSearch.Value);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        Response.Redirect("searchResults.aspx?keyword=" + txtSearch.Value);
    }
    #endregion
}
